package com.test.base.netty_upgrade.selfprotocol.protocol;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * description 一个chatServer
 * @author zken
 * @CreateDate 2024/11/21 23:28:38
 */
public class ChatServer {
    public static void main(String[] args) {
        // 日志处理器
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        // 使用的协议为MessageCodecSharable种使用的解码和编码方法
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(
                                1024, 12, 4, 0, 0
                        ));
                        // 加入消息编解码器件
                        ch.pipeline().addLast(MESSAGE_CODEC);
                        ch.pipeline().addLast(LOGGING_HANDLER);
                    }
                });
        try {
            // 启动
            ChannelFuture future = bootstrap.bind(8080).sync();
            Channel channel = future.channel();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
